<script>
import Config from '@/config/index.js'
import { uploadAReceipt } from '@/api/api.js'

export default {
  name: "upload",
  data() {
    return {
      // 选择的图片路径
      imgList: [],
      // 提示信息列表
      tips: [
        '拍照请保持小票凭证内容清晰，不可有阴影、遮挡或涂改。拍摄内容需包含完整【店铺名称】、【消费时间】、【消费金额】及【消费单号】。',
        '如果小票过长，可折叠商品明细部分。',
        '仅支持店铺消费小票正本，不支持在线支付截图、发票、银行刷卡联等作为积分凭证（如有特殊情况，请转人工审核）。',
        '充值、团购订单、外卖平台点单不适用于本规则。',
        '仅支持7日内（含7日）消费凭证，过期小票将被拒绝。',
        '单笔消费仅可积分一次。'
      ],
      uploading: false,
      showCamera: false, // 是否显示相机
      photo: '' // 拍照临时路径
    }
  },
  onLoad() {
    uni.setNavigationBarTitle({
      title: this.$t('receiptPoints.uploadPage.title')
    });
  },
  watch: {
    // 监听语言变化，更新导航栏标题
    '$i18n.locale'() {
      uni.setNavigationBarTitle({
        title: this.$t('receiptPoints.uploadPage.title')
      })
    }
  },
  methods: {
    // 选择图片或重新上传
    chooseImg() {
      // 如果正在上传中，禁止操作
      if (this.uploading) {
        uni.showToast({
          title: this.$t('receiptPoints.uploadPage.upload.uploading2'),
          icon: 'none'
        });
        return;
      }

      // 无论是否已经有图片，都弹出选择菜单
      uni.showActionSheet({
        itemList: [this.$t('receiptPoints.uploadPage.camera.takePhoto'), this.$t('receiptPoints.uploadPage.camera.fromAlbum')],
        success: (res) => {
          if (res.tapIndex === 0) {
            // 打开相机全屏模式
            this.showCamera = true;
            // 设置导航栏为透明
            uni.setNavigationBarColor({
              frontColor: '#ffffff',
              backgroundColor: '#000000',
              animation: {
                duration: 300,
                timingFunc: 'easeIn'
              }
            });
          } else {
            // 从相册选择
            uni.chooseImage({
              count: 1,
              sizeType: ['original', 'compressed'],
              sourceType: ['album'],
              success: (res) => {
                this.uploadImage(res.tempFilePaths[0]);
              }
            });
          }
        }
      });
    },

    // 取消相机
    cancelCamera() {
      this.showCamera = false;
      // 恢复导航栏颜色
      uni.setNavigationBarColor({
        frontColor: '#000000',
        backgroundColor: '#ffffff',
        animation: {
          duration: 300,
          timingFunc: 'easeOut'
        }
      });
    },

    // 处理拍照
    takePhoto() {
      const cameraContext = uni.createCameraContext(this);

      // 拍照
      cameraContext.takePhoto({
        quality: 'high', // 照片质量: high, medium, low
        success: (res) => {
          this.photo = res.tempImagePath;
          this.showCamera = false; // 关闭相机预览
          // 恢复导航栏颜色
          uni.setNavigationBarColor({
            frontColor: '#000000',
            backgroundColor: '#ffffff',
            animation: {
              duration: 300,
              timingFunc: 'easeOut'
            }
          });
          this.uploadImage(res.tempImagePath);
        },
        fail: (err) => {
          console.log('拍照失败', err);
          uni.showToast({
            title: this.$t('receiptPoints.uploadPage.camera.takePhotoFailed'),
            icon: 'none'
          });
          this.showCamera = false;
          // 恢复导航栏颜色
          uni.setNavigationBarColor({
            frontColor: '#000000',
            backgroundColor: '#ffffff',
            animation: {
              duration: 300,
              timingFunc: 'easeOut'
            }
          });
        }
      });
    },

    // 相机错误处理
    onCameraError(e) {
      console.log('摄像头发生错误', e.detail);
      uni.showToast({
        title: this.$t('receiptPoints.uploadPage.camera.error'),
        icon: 'none'
      });
      this.showCamera = false;
      // 恢复导航栏颜色
      uni.setNavigationBarColor({
        frontColor: '#000000',
        backgroundColor: '#ffffff',
        animation: {
          duration: 300,
          timingFunc: 'easeOut'
        }
      });
    },

    // 上传图片
    uploadImage(filePath) {
      let _this = this;
      this.uploading = true;
      uni.showLoading({
        title: this.$t('receiptPoints.uploadPage.upload.uploading'),
        mask: true
      });

      // 先上传图片到服务器临时存储
      uni.uploadFile({
        url: Config.baseUrl + '/API/Users/PictureUpload',
        filePath: filePath,
        name: 'file',
        success: (uploadFileRes) => {
          try {
            let imgList = JSON.parse(uploadFileRes.data);
            // 替换已有图片，确保只有一张
            _this.imgList = [imgList.picturePath];
            uni.hideLoading();
            _this.uploading = false;

            uni.showToast({
              title: this.$t('receiptPoints.uploadPage.upload.success'),
              icon: 'success'
            });
          } catch (e) {
            console.error('上传响应解析错误:', e);
            uni.hideLoading();
            _this.uploading = false;

            uni.showToast({
              title: this.$t('receiptPoints.uploadPage.upload.failed'),
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          console.error('上传失败:', err);
          uni.hideLoading();
          _this.uploading = false;

          uni.showToast({
            title: this.$t('receiptPoints.uploadPage.upload.failed'),
            icon: 'none'
          });
        }
      });
    },

    // 预览图片
    previewImg(url) {
      uni.previewImage({
        urls: [url],
        longPressActions: {
          itemList: [this.$t('userInfo.edit.preview.send'), this.$t('userInfo.edit.preview.saveImage'), this.$t('userInfo.edit.preview.favorite')],
          success: function(data) {
            console.log('选中了第' + (data.tapIndex + 1) + '个按钮');
          },
          fail: function(err) {
            console.log(err.errMsg);
          }
        }
      });
    },

    // 确认上传
    confirmUpload() {
      if (this.imgList.length === 0) {
        uni.showToast({
          title: this.$t('receiptPoints.uploadPage.upload.pleaseUpload'),
          icon: 'none'
        });
        return;
      }

      if (this.uploading) {
        uni.showToast({
          title: this.$t('receiptPoints.uploadPage.upload.uploading2'),
          icon: 'none'
        });
        return;
      }

      // 显示加载中
      uni.showLoading({
        title: this.$t('receiptPoints.uploadPage.upload.submitting'),
        mask: true
      });

      // 调用uploadAReceipt API提交小票数据
      uploadAReceipt({
        InvoiceImg: this.imgList[0]
      }).then(res => {
        uni.hideLoading();

        uni.showToast({
          title: this.$t('receiptPoints.uploadPage.upload.submitSuccess'),
          icon: 'success'
        });

        // 返回上一页，回到列表页面
        setTimeout(() => {
          uni.navigateBack();
        }, 1500);
      }).catch(err => {
        uni.hideLoading();
        console.error('提交小票失败:', err);

        uni.showToast({
          title: this.$t('receiptPoints.uploadPage.upload.submitFailed'),
          icon: 'none'
        });
      });
    }
  }
}
</script>

<template>
  <view class="container">
    <!-- 摄像头全屏显示区域 -->
    <view v-if="showCamera" class="camera-fullscreen">
      <camera id="camera" device-position="back" flash="off" binderror="onCameraError"></camera>
      <view class="camera-controls">
        <view class="camera-btn-cancel" @click="cancelCamera">{{$t('receiptPoints.uploadPage.camera.cancel')}}</view>
        <view class="camera-btn-take" @click="takePhoto"></view>
      </view>
    </view>

    <!-- 正常上传界面 -->
    <block v-else>
      <!-- 上传步骤提示 -->
      <view class="step-title">
        <text class="step-number">{{$t('receiptPoints.uploadPage.stepTitle')}}</text>
        <text class="step-desc">{{$t('receiptPoints.uploadPage.stepDesc')}}</text>
      </view>

      <!-- 上传区域 -->
      <view class="upload-area">
        <!-- 左侧上传框 -->
        <view class="upload-box">
          <view class="imgBox">
            <!-- 已选择图片的显示 -->
            <view class="imgMenu" v-if="imgList.length > 0">
              <view class="renderImg">
                <image :src="imgList[0]" mode="aspectFill" @click="previewImg(imgList[0])"></image>
              </view>
              <!-- 重新上传按钮 -->
              <view class="reupload-btn" @click.stop="chooseImg()">
                <image src="/static/edit.png" mode="aspectFit"></image>
                <text>{{$t('receiptPoints.uploadPage.reupload')}}</text>
              </view>
            </view>

            <!-- 初始上传按钮 -->
            <view v-if="imgList.length === 0" class="imgMenu upload-btn" @click="chooseImg()">
              <view class="upload-placeholder">
                <view class="upload-icon">+</view>
                <text class="upload-text">{{$t('receiptPoints.uploadPage.clickUpload')}}</text>
              </view>
            </view>
          </view>
        </view>

        <!-- 右侧示例图片 -->
        <view class="example-box">
          <image src="https://bpic.588ku.com/element_origin_min_pic/23/04/25/412038e25b3d640988c703d79b0d6923.jpg" mode="widthFix" class="example-image"></image>
          <text class="example-text">{{$t('receiptPoints.uploadPage.example')}}</text>
        </view>
      </view>

      <!-- 温馨提示区域 -->
      <view class="tips-container">
        <view class="tips-title">
          <view class="tips-title-bar"></view>
          <text class="tips-title-text">{{$t('receiptPoints.uploadPage.tipsTitle')}}</text>
        </view>

        <view class="tips-list">
          <view class="tip-item" v-for="(tip, index) in tips" :key="index">
            <text class="tip-number">{{index + 1}}.</text>
            <text class="tip-content">{{$t(`receiptPoints.rules.tips.${index}`)}}</text>
          </view>
        </view>
      </view>

      <!-- 确认按钮 -->
      <view class="confirm-btn-area">
        <button class="confirm-btn" @click="confirmUpload">{{$t('receiptPoints.uploadPage.confirmUpload')}}</button>
      </view>
    </block>
  </view>
</template>

<style scoped lang="scss">
.container {
  min-height: 100vh;
  background-color: #F5F6F7;
  padding: 30rpx;
  position: relative;
}

/* 相机全屏样式 */
.camera-fullscreen {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100vh;
  z-index: 999;
  background-color: #000;

  camera {
    width: 100%;
    height: 100%;
  }

  .camera-controls {
    position: absolute;
    bottom: 80rpx;
    left: 0;
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;

    .camera-btn-cancel {
      position: absolute;
      left: 60rpx;
      color: #ffffff;
      font-size: 32rpx;
    }

    .camera-btn-take {
      width: 140rpx;
      height: 140rpx;
      border-radius: 50%;
      background-color: rgba(255, 255, 255, 0.8);
      border: 12rpx solid rgba(255, 255, 255, 0.3);

      &:active {
        transform: scale(0.95);
        background-color: #fff;
      }
    }
  }
}

/* 步骤标题样式 */
.step-title {
  margin-bottom: 30rpx;

  .step-number {
    font-size: 36rpx;
    font-weight: 600;
    color: #333;
    margin-right: 10rpx;
  }

  .step-desc {
    font-size: 28rpx;
    color: #999;
  }
}

/* 上传区域样式 */
.upload-area {
  display: flex;
  margin-bottom: 40rpx;

  .upload-box {
    flex: 1;
    background-color: #fff;
    border-radius: 12rpx;
    padding: 30rpx;
    margin-right: 20rpx;
    height: 400rpx;
    position: relative;

    .imgBox {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      gap: 30rpx;
      position: relative;

      .imgMenu {
        width: 100%;
        height: 100%;
        position: relative;
        background: #f5f5f5;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 12rpx;
        transition: all 0.3s ease;
        overflow: hidden;

        &:active {
          transform: scale(0.98);
        }

        .renderImg {
          width: 100%;
          height: 100%;
          border-radius: 12rpx;
          overflow: hidden;
          box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);

          image {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
        }

        /* 重新上传按钮 */
        .reupload-btn {
          position: absolute;
          bottom: 20rpx;
          right: 20rpx;
          background-color: rgba(0, 0, 0, 0.6);
          color: #fff;
          font-size: 24rpx;
          padding: 8rpx 16rpx;
          border-radius: 30rpx;
          display: flex;
          align-items: center;
          z-index: 2;

          image {
            width: 28rpx;
            height: 28rpx;
            margin-right: 8rpx;
          }

          text {
            line-height: 1;
          }
        }

        &.upload-btn {
          background: #f8f8f8;
          border: 2rpx dashed #ddd;

          .upload-placeholder {
            display: flex;
            flex-direction: column;
            align-items: center;

            .upload-icon {
              font-size: 60rpx;
              color: #ccc;
              line-height: 1;
              margin-bottom: 10rpx;
            }

            .upload-text {
              font-size: 24rpx;
              color: #999;
              text-align: center;
            }
          }
        }
      }
    }
  }

  .example-box {
    width: 280rpx;
    background-color: #fff;
    border-radius: 12rpx;
    padding: 20rpx;
    display: flex;
    flex-direction: column;
    align-items: center;

    .example-image {
      width: 100%;
      height: 300rpx;
      margin-bottom: 10rpx;
    }

    .example-text {
      font-size: 24rpx;
      color: #999;
    }
  }
}

/* 温馨提示区域 */
.tips-container {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 80rpx;

  .tips-title {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;

    .tips-title-bar {
      width: 8rpx;
      height: 32rpx;
      background-color: #f9ae3d;
      border-radius: 4rpx;
      margin-right: 16rpx;
    }

    .tips-title-text {
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
    }
  }

  .tips-list {
    .tip-item {
      display: flex;
      margin-bottom: 20rpx;

      &:last-child {
        margin-bottom: 0;
      }

      .tip-number {
        font-size: 28rpx;
        color: #333;
        flex-shrink: 0;
        margin-right: 8rpx;
      }

      .tip-content {
        font-size: 28rpx;
        color: #666;
        line-height: 1.5;
      }
    }
  }
}

/* 确认按钮 */
.confirm-btn-area {
  padding: 0 30rpx;

  .confirm-btn {
    width: 100%;
    height: 90rpx;
    line-height: 90rpx;
    background: linear-gradient(135deg, #498FFF 0%, #3A7FE6 100%);
    color: #fff;
    font-size: 32rpx;
    border-radius: 45rpx;
    border: none;
    transition: all 0.3s ease;

    &:active {
      transform: translateY(2rpx);
      box-shadow: 0 2rpx 8rpx rgba(73,143,255,0.2);
    }
  }
}
</style>
